<template>
  <el-card v-loading="loading" body-style="flex:1;" class="unknown-water-card">
    <template #header>
      <span>不明水分摊计算</span>
      <el-tooltip content="设置不明水分摊规则">
        <el-button type="primary" size="small" @click="dialogVisible = true">
          <template #icon>
            <SvgIcon icon="setting"></SvgIcon>
          </template>
          设置分摊规则
        </el-button>
      </el-tooltip>
    </template>

    <div class="scrollbar-wrapper">
      <div class="unknown-water-summary">
        <!-- 统计数据部分 -->
        <div class="statistics-section">
          <div class="summary-item">
            <div class="label">总用水量</div>
            <div class="value">{{ waterData.totalUsage }}m³</div>
          </div>
          <div class="summary-item">
            <div class="label">不明水量 ({{ percentage }}%)</div>
            <div class="value">{{ waterData.unknownUsage }}m³</div>
          </div>
        </div>
        <el-divider />
        <div class="distribution-section">
          <template v-if="waterData.distribution.length">
            <div class="distribution-list">
              <div v-for="item in waterData.distribution" :key="item.name" class="distribution-item">
                <div class="item-header">
                  <span class="name">{{ item.name }}</span>
                  <span class="ratio">占比: {{ item.ratio }}%</span>
                </div>
                <div class="item-details">
                  <div class="detail-row">
                    <span class="label">分摊水量:</span>
                    <span class="value highlight">{{ item.share }}m³</span>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <el-empty description="未设置分摊规则" :image-size="100">
              <el-button type="primary" @click="dialogVisible = true">
                设置规则
              </el-button>
            </el-empty>
          </template>
        </div>
      </div>
    </div>
  </el-card>

  <UnknownWaterDialog v-model="dialogVisible" :current-method="currentMethod" @confirm="handleDistributionConfirm" />
</template>

<script setup>
import { ref, computed, watchEffect } from "vue";
import { getUnknownWaterApi } from "@/api/algorithm";
import { handleError } from "@/utils/handleError";
import { useEnergyUsersStore } from "@/stores/energyUser";
import UnknownWaterDialog from "./components/UnknownWaterDialog.vue";
import { useCompanyStore } from "@/stores/company";
import { updateEnergyUsersApi } from "@/api/energy_users";
import SvgIcon from "@/components/icon/SvgIcon.vue";

let loading = ref(false);
let props = defineProps({
  dateRange: {
    type: Array,
    default: () => [],
  },
});

let energyUsersStore = useEnergyUsersStore();
let unknownUsage = ref(0);
let totalUsage = ref(0);
let errorMessage = ref('');
let companyStore = useCompanyStore();

watchEffect(async () => {
  if (props.dateRange.length && companyStore.currentCompany) {
    await getUnknownWaterData();
  }
});

// 获取不明水数据
async function getUnknownWaterData() {
  try {
    loading.value = true;
    const res = await getUnknownWaterApi({
      id: companyStore.currentCompany.id,
      start_time: props.dateRange[0],
      end_time: props.dateRange[1]
    });

    totalUsage.value = parseFloat(res.data.top_usage).toFixed(2);
    unknownUsage.value = parseFloat(res.data.unknown_water).toFixed(2);
    errorMessage.value = res.data.errors || '';
  } catch (error) {
    handleError(error, "获取不明水数据失败");
  } finally {
    loading.value = false;
  }
}

const waterData = computed(() => ({
  totalUsage: totalUsage.value,
  unknownUsage: unknownUsage.value,
  distribution: energyUsersStore.energyUserList.filter((item) => +item.unknown_ratio).map((item) => ({
    id: item.id,
    name: item.name,
    ratio: (item.unknown_ratio * 100).toFixed(2),
    share: (item.unknown_ratio * unknownUsage.value).toFixed(2),
  })),
}));

// 状态管理
const dialogVisible = ref(false);
const currentMethod = ref("water");

// 计算属性
const percentage = computed(() => {
  return (
    (waterData.value.unknownUsage / waterData.value.totalUsage) *
    100
  ).toFixed(2);
});

const handleDistributionConfirm = async (data) => {
  currentMethod.value = data.method;
  try {
    loading.value = true;
    await Promise.all(waterData.value.distribution.map((item) => {
      return updateEnergyUsersApi({
        id: item.id,
        unknown_ratio: '0',
      })
    }))
    await Promise.all(data.users.map(async (item) => {
      return updateEnergyUsersApi({
        id: item.id,
        unknown_ratio: '' + item.ratio / 100,
      })
    }))

    await energyUsersStore.fetchEnergyUsers()
    ElMessage.success("设置分摊规则成功")
  } catch (error) {
    handleError(error, "设置分摊规则失败")
  } finally {
    loading.value = false;
    dialogVisible.value = false;
  }
};
</script>

<style scoped>
.unknown-water-card {
  height: 100%;
  min-height: 390px;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scrollbar-wrapper {
  overflow-y: auto;
}

.unknown-water-summary {
  padding: 16px;
}

.statistics-section {
  margin-bottom: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.summary-item .label {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.summary-item .value {
  color: var(--el-text-color-primary);
  font-weight: 600;
  font-size: 16px;
}

.error-item {
  background-color: var(--el-color-danger-light-9);
}

.error-text {
  color: var(--el-color-danger);
  font-size: 14px;
  font-weight: normal;
  white-space: pre-line;
}

.distribution-section {
  margin-top: 16px;
}

.method-info {
  margin-bottom: 16px;
  padding: 12px;
  background-color: var(--el-color-primary-light-9);
  border-radius: 4px;
  color: var(--el-color-primary);
  font-size: 14px;
}

.distribution-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.distribution-item {
  padding: 16px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.distribution-item:hover {
  background-color: var(--el-fill-color);
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.item-header .name {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.item-header .ratio {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-row .label {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.detail-row .value {
  font-size: 14px;
}

.detail-row .highlight {
  color: var(--el-color-primary);
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>